﻿using Freshbox2._0.MODEL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Freshbox2._0.UI.Controllers
{
    //父类 里的 虚方法  来为子类继承
    public class BaseController<T> : Controller where T : BaseModel
    {
        //protected virtual admin CurrentUer
        //{
        //    get { return Session["CurrentUer"] == null ? null : (admin)Session["CurrentUer"]; }
        //}

        public virtual BLL.BaseBll<T> bll { get; set; }

        //Index页面
        public virtual ActionResult Index()
        {
            return View();
        }
        //获取数据
        public virtual ActionResult Get(int page, int rows, T model)
        {
            int count;
            var list = bll.Search(model, x => true, true, x => x.ID, rows, page, out count).ToList();
            return Json(new { total = count, rows = list });
        }
        //添加方法
        public virtual ActionResult Save(T model)
        {
            string msg = "添加失败";
            string state = "false";
            ModelState.Remove("ID");
            if (ModelState.IsValid)
            {
                if (bll.Add(model) > 0)
                {
                    msg = "添加成功";
                    state = "true";
                }

            }
            return Json(new { state = state, msg = msg });
        }
        //修改方法
        public virtual ActionResult Modify(T model)
        {
            string msg = "修改失败";
            string state = "false";
            if (ModelState.IsValid)
            {
                if (bll.Modify(model) > 0)
                {
                    msg = "修改成功";
                    state = "true";
                }
            }
            return Json(new { state = state, msg = msg });
        }

        //删除方法

        public virtual ActionResult Del(string ids)
        {
            int[] id = Array.ConvertAll<string, int>(ids.Split(','), x => int.Parse(x));

            string msg = "删除失败";
            string state = "false";
            if (bll.Delete(x => id.Contains(x.ID)) > 0)
            {
                msg = "删除成功";
                state = "true";
            }
            return Json(new { state = state, msg = msg });

        }
        //获取一条数据
        public virtual ActionResult GetOne(int id)
        {
            return Json(bll.Search(x => x.ID == id).ToList()[0], JsonRequestBehavior.AllowGet);
        }

    }
}
